package com.lagou.rocket.init;

import com.lagou.rocket.dao.ProductDao;
import com.lagou.rocket.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class ProductInit implements ApplicationRunner {

    @Autowired
    private ProductDao productDao;

    @Autowired
    private RedisTemplate redisTemplate;

    private final String PRODUCT_NUM = "productNum:";

    /**
     * 初始化商品数量到缓存
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {

        List<Product> productList = productDao.findAll();

        productList.stream().forEach(product -> {
            String key = PRODUCT_NUM + product.getId();
            redisTemplate.opsForValue().set(key, product.getNum());
        });
    }
}
